package com.mengxuegu.springboot.Controller;

import com.mengxuegu.springboot.entities.User;
import com.mengxuegu.springboot.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {
    Logger logger = LoggerFactory.getLogger(this.getClass());

//

//    @Autowired
//    UserMapper userMapper;


    @Autowired
    UserMapper userMapper;

    @GetMapping("/users")
    public String list(Map<String,Object> map , User user ){

        List<User> userList = userMapper.getUserList(user);
        map.put("users",userList);
        map.put("username",user.getUsername());
        logger.info("users  查询:  "+userList);
        return "user/list";
    }


    //去到查询或者更新页面
    @GetMapping("/user/{id}")
    public String toUser(Map<String,Object> map, @PathVariable Integer id , @RequestParam(defaultValue = "view") String view){
        User userById = userMapper.getUserById(id);
        map.put("user", userById);
        return "user/"+view;
    }

    //更新用户user
    @PutMapping("/user")
    public  String update(User user){
        int i = userMapper.updateUser(user);
        logger.info("更新用户user : " + user);
        return "redirect:/users";
    }

    //去user添加页面
    @GetMapping("/user")
    public String toAddUser(){
        return "user/add";
    }


    //添加用户
    @PostMapping("/user")
    public String addUser(User user){
        userMapper.addUser(user);
        logger.info("添加用户 : "+user);
        return "redirect:/users";
    }

    //删除用户
    @DeleteMapping("/user/{id}")
    public String deleteUser(@PathVariable Integer id){
        int i = userMapper.deleteUser(id);
        logger.info("删除User  " + id);
        return "redirect:/users";
    }


    //旧密码验证
    @ResponseBody
    @GetMapping("/user/pwd/{oldPassword}")
    public  Boolean oldPassword(HttpSession session, @PathVariable String oldPassword){
        Integer id = (Integer)session.getAttribute("sessionuserid");

        User userById = userMapper.getUserById(id);


        if (userById.getPassword().equals(oldPassword)) {
            return true;
        }


        return false;
    }


    //修改密码

    @PostMapping("/user/pwd")
    public String updaePassword( User user){
        int i = userMapper.updatePassword(user);
        logger.info("修改密码  : " + user);
        return "redirect:/users";

    }


    @GetMapping("/main")
    public String repassword(){
        return "main/password";
    }
}
